package easyexcel;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import easyexcel.exception.FileStopException;
import easyexcel.exportexcel.EasyExcelExport;
import easyexcel.exportexcel.EasyExportBean;
import easyexcel.exportexcel.EasyExportExcelHandle;
import easyexcel.exportexcel.ExportConfigBean;
import easyexcel.exportexcel.ExportTaskBean;
import easyexcel.importexcel.EasyExcelImport;
import easyexcel.importexcel.EasyExcelImportListener;
import easyexcel.importexcel.EasyImportBean;
import easyexcel.importexcel.ImportBatchBean;
import easyexcel.importexcel.ImportConfigBean;
import easyexcel.importexcel.ImportTaskBean;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class CommonExcelService {

    //    @Autowired
    //    private OssFileAdapter ossFileAdapter;
    //
    //    @Autowired
    //    private FileStopService fileStopService;
    //
    //    @Autowired
    //    private FileConfigService fileConfigService;
    //
    //    @Autowired
    //    private ExportTaskDao exportTaskDao;
    //
    //    @Autowired
    //    private ImportTaskDao importTaskDao;

    public <E, P> void easyExport(EasyExportBean<E, P> exportBean) {
        //获取数据库的导出记录
        ExportTaskBean taskBean = new ExportTaskBean();
        //exportTaskDao.selectByKey(exportBean.getExportId());

        //        if (taskBean == null) {
        //            return;
        //        }
        // 设置处理时间
        //        taskBean.setExecuteTime(new Date());
        //        taskBean.setFileName(exportBean.getFileName());
        //        taskBean.setFileFormat(".xlsx");

        //导出文件上传oss
        //OSSBean ossBean = new OSSBean(taskBean.getBizType(), taskBean.getTaskType(), taskBean.getUpdateDttm());

        //获取导出配置
        ExportConfigBean config = new ExportConfigBean();
        //fileConfigService.getExportConfig(taskBean.getBizType(), taskBean.getTaskType());

        try {
            EasyExcelExport.<E, P>bulider()
                    .setClz(exportBean.getClz())
                    .setSheetName(exportBean.getSheetName())
                    .setPageSize(config.getPageSize())
                    .setMaxSheetLine(config.getMaxSheetLine())
                    .setLimitAllSheetLine(config.getLimitAllSheetLine())
                    .setExportHandle(new EasyExportExcelHandle<E, P>() {

                        public List<E> loadData(EasyExcelExport.ExportContext<E, P> context) {
                            //                            if (fileStopService.isStopExport(exportBean.getExportId())) {
                            //                                throw new FileStopException("终止导出任务id=" + exportBean.getExportId());
                            //                            }
                            return exportBean.getHandle().handle(context, taskBean);
                        }

                        @Override
                        public List<P> getPartition() {
                            return exportBean.getPartition();
                        }

                        public WriteTable getWriteTable() {
                            List<List<String>> header = exportBean.getHeader();
                            if (CollectionUtils.isEmpty(header)) {
                                return null;
                            }
                            WriteTable writeTable = new WriteTable();
                            writeTable.setTableNo(0);
                            writeTable.setHead(header);
                            return writeTable;
                        }

                        public void afterExportData(EasyExcelExport.ExportContext<E, P> context) {
                            //                            String objectId = ossFileAdapter.uploadFile(context.getFile(), ossBean);
                            //                            taskBean.setFileObjectId(objectId);
                            //                            taskBean.setTaskStatus(FileConstants.ExportType.FINISHED.code());
                            //                            taskBean.setUpdateDttm(new Date());
                            //                            exportTaskDao.updateByKey(taskBean);
                        }
                    })
                    .create()
                    .export(exportBean.getFileName());
        } catch (Exception fe) {
            log.error("", fe);
            taskBean.setUpdateDttm(new Date());
            //taskBean.setTaskStatus(FileConstants.ExportType.STOP.code());
            //exportTaskDao.updateByKey(taskBean);
        }
    }

    /**
     * easyexcel导入
     *
     * @param importBean
     * @param <E>
     */
    public <E> void easyImport(EasyImportBean<E> importBean) {
        final ImportTaskBean importTaskBean = new ImportTaskBean();
        //= importTaskDao.selectByKey(importBean.getImportId());
        // 执行时间
        importTaskBean.setExecuteTime(new Date());

        //OSSBean ossBean = new OSSBean(importTaskBean.getBizType(), importTaskBean.getTaskType(), importTaskBean.getUpdateDttm());

        ImportConfigBean config = new ImportConfigBean();
        //fileConfigService.getImportConfig(importTaskBean.getBizType(), importTaskBean.getTaskType());

        File tmpFile = null;
        try {
            tmpFile = File.createTempFile(System.currentTimeMillis() + "-".concat(importBean.getImportId().toString()), ".xlsx");
            // 获取记录的objectId
            InputStream inputStream = new InputStream() {
                @Override
                public int read() throws IOException {
                    return 0;
                }
            };
            //ossFileAdapter.downloadFile(importTaskBean.getFileObjectId(), ossBean);
            //
            AtomicInteger total = new AtomicInteger(0);
            AtomicInteger error = new AtomicInteger(0);
            //导入存在错误的记录
            ExcelWriter excelWriter = EasyExcel.write(tmpFile, importBean.getClz()).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "error").build();

            EasyExcelImport.load(inputStream, importBean.getClz(), config.getHeaderLine(), new EasyExcelImportListener<E>() {
                @Override
                protected void parseData() {
                    //                    if (fileStopService.isStopLoad(importBean.getImportId())) {
                    //                        throw new FileStopException("终止导入任务id=" + importBean.getImportId());
                    //                    }
                    ImportBatchBean<E> batchBean = importBean.getHandle().handle(getDataList(), importTaskBean);
                    int errorCount = batchBean.getErrorCount();
                    if (errorCount > 0) {
                        excelWriter.write(batchBean.getErrorList(), writeSheet);
                    }
                    total.set(total.get() + batchBean.getTotal());
                    error.set(error.get() + errorCount);
                }
            });

            excelWriter.finish();
            if (error.get() != 0) {
                // 如果存在错误的情况下 上传错误文件
                //importTaskBean.setErrorFileObjectId(ossFileAdapter.uploadFile(tmpFile, ossBean));
            }

            int totalNum = total.get();
            int errorNum = error.get();
            int successNum = totalNum - errorNum;
            if (errorNum == 0) {
                //importTaskBean.setTaskStatus(FileConstants.ImportType.FINISHED.code());
            } else {
                if (successNum > 0) {
                    //importTaskBean.setTaskStatus(FileConstants.ImportType.PARTIAL_FAIL.code());
                } else {
                    //importTaskBean.setTaskStatus(FileConstants.ImportType.FAIL.code());
                }
            }
            importTaskBean.setTotalCount(totalNum);
            importTaskBean.setFailNum(errorNum);
            importTaskBean.setSuccessNum(successNum);
            importTaskBean.setUpdateDttm(new Date());
            //importTaskDao.updateByKey(importTaskBean);
        } catch (FileStopException fe) {
            log.error("", fe);
            importTaskBean.setUpdateDttm(new Date());
            //importTaskBean.setTaskStatus(FileConstants.ImportType.STOP.code());
            //importTaskDao.updateByKey(importTaskBean);
        } catch (Exception e) {
            log.error("导入excel失败", e);
            importTaskBean.setUpdateDttm(new Date());
            //importTaskBean.setTaskStatus(FileConstants.ImportType.SYSTEM.code());
            //importTaskDao.updateByKey(importTaskBean);
        } finally {
            if (tmpFile != null) {
                try {
                    tmpFile.delete();
                } catch (Exception e) {
                    log.error("删除文件失败", e);
                }
            }
        }
    }
}
